import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import common from './common.js'
const store = new Vuex.Store({
	state: {
		serverTime: {},
		applyMsgs: [], //申请消息
		friends: [], //好友（这里只存id,全部引用users数据，形成引用)
		newMessage: [], //最新的私聊消息
		groups: [], //群组
		loginUser: {}, //登录用户
		connected: false, //是否已连接
		users: [], //所有用户（包括好友和非好友，非好友有可能是群组成员或者以前的群组成员但又不是好友的用户）
		chatMessageAsync: {}, //与服务器的消息同步状态
		version: null, //版本
		token: '', //令牌
		publicKey: '', //RSA公钥
		maxId: 0, //最大ID
		runBehind: false, //是否后台运行
		updating: false //更新中
	},
	mutations: {
		//设置令牌
		setToken(state, token) {
			state.token = token;
		},
		//设置版本
		setVersion(state, data) {
			state.version = data;
		},
		//设置服务器时间
		setServerTime(state, data) {
			state.serverTime = data;
		},
		//设置后台运行
		setRunBehind(state, data) {
			state.runBehind = data;
		},
		//设置申请消息
		setApplyMsg(state, data) {
			if (Array.isArray(data)) {
				let items = [];
				for (let item of data) {
					//将不存在的数据添加到列表中
					if (!state.applyMsgs.some(c => c.Id == item.Id)) {
						items.push(item);
					}
				}
				state.applyMsgs.push(...items);
			} else {
				//如果存在相同数据则不添加
				if (state.applyMsgs.some(c => c.Id == data.Id)) {
					return;
				}
				let index = Math.max(0, state.applyMsgs.findIndex(c => c.Id < data.Id));
				state.applyMsgs.splice(index, 0, data);
			}
		},
		//设置公钥
		setPublicKey(state, data) {
			state.publicKey = data;
		},
		//设置好友
		setFriends(state, data) {
			//先将数据添加至用户列表中
			this.commit('setUsers', data);
			if (Array.isArray(data)) {
				data.forEach(item => {
					if (!state.friends.includes(item.Id)) {
						state.friends.push(item.Id);
					}
				});
			} else if (typeof data === 'number') {
				let index = state.friends.findIndex(c => c == data);
				if (index >= 0) {
					state.friends.splice(index, 1);
				}
			} else {
				if (!state.friends.includes(data.Id)) {
					state.friends.push(data.Id);
				}
			}
		},
		//设置用户
		setUsers(state, data) {
			if (Array.isArray(data)) {
				for (let item of data) {
					if (!state.users.some(c => c.Id == item.Id)) {
						state.users.push(item);
					}
				}
			} else if (typeof data === 'object') {
				if (!state.users.some(c => c.Id == data.Id)) {
					state.users.push(data);
				}
			}
		},
		//设置最大ID
		setMaxId(state, data) {
			state.maxId = data;
		},
		//设置是否连接
		setConnected(state, data) {
			state.connected = data;
		},
		//设置同步状态
		chatMessageAsync(state, data) {
			if (undefined === data.other) {
				state.chatMessageAsync = {};
			} else {
				state.chatMessageAsync[`${data.other}_${data.type}`] = data.data;
			}
		},
		//设置用户信息
		setUserInfo(state, data) {
			for (let key in data) {
				state.loginUser[key] = data[key];
			}
		},
		//设置最新消息
		setNewMessage(state, data) {
			let list = state.newMessage.map(item => Object.assign({}, item));
			if (Array.isArray(data)) {
				data.forEach(item => {
					if (typeof item.time === 'string') {
						item.time = common.parseDate(item.time);
					}
				});
				list.push(...data);
				state.newMessage.push(...data);
			} else {
				if (typeof data.time === 'string') {
					item.time = common.parseDate(data.time);
				}
				//如果是单条数据则更新
				let old = list.find(c => c.other == data.other && c.type == data.type);
				if (old) {
					if (old.time > data.time) {
						return;
					}
					//如果有数据的话则更新
					old.id = data.id;
					old.read = data.read;
					old.content = data.content;
					old.messageType = data.messageType;
					old.time = data.time;
					old.state = data.state;
					old.msgcount += data.msgcount;
				} else {
					//如果没有的话则添加
					list.push(data);
				}
			}
			state.newMessage.splice(0, state.newMessage.length, ...list.sort((a, b) => {
				return a.time < b.time ? 1 : -1;
			}));
		},
		//移除最新消息
		removeNewMessage(state, data) {
			const index = state.newMessage.findIndex(c => c.other == data.other && c.type == data.type);
			if (index >= 0) {
				state.newMessage.splice(index, 1);
			}
		},
		//强制设置最新消息
		forceSetNewMessage(state, data) {
			const old = state.newMessage.find(c => c.other == data.other && c.type == data.type);
			if (old) {
				old.time = new Date(1990, 1, 1);
				this.commit('setNewMessage', data);
			}
		},
		//设置未读数
		setUnreadCount(state, data) {
			let item = state.newMessage.find(c => c.other == data.other && c.type == data.type);
			item && (item.msgcount = data.msgcount)
		},
		//设置群组
		setGroups(state, data) {
			if (Array.isArray(data)) {
				state.groups.push(...data);
			} else {
				if (!state.groups.some(c => c.Id == data.Id)) {
					state.groups.push(data);
				}
			}
		},
		//设置登录用户
		setLoginUser(state, data) {
			state.loginUser = data;
		},
		//设置更新
		setUpdating(state, data) {
			state.updating = data;
		},
		//重置
		reset(state) {
			state.applyMsgs = [];
			state.friends = [];
			state.newMessage = [];
			state.groups = [];
			state.loginUser = {};
			state.token = '';
			state.users = [];
			state.connected = false;
			state.chatMessageAsync = {};
		}
	}
})
export default store
